/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React, {useEffect} from 'react';
import type {PropsWithChildren} from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Platform,
  ToastAndroid,
  TouchableOpacity,
  DeviceEventEmitter,
  NativeModules,
  PermissionsAndroid,
} from 'react-native';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import {GestureHandlerRootView} from 'react-native-gesture-handler';
import {Provider} from 'react-redux';
import {TopView, Theme} from 'teaset';
import {NavigationContainer} from '@react-navigation/native';
import {navigationRef} from './app/utils/RootNavigation';
import {createStackNavigator} from '@react-navigation/stack';
import MainScreen from './app/screens/MainScreen';
import {store} from './app/store/store';
import {PushyProvider, Pushy, usePushy} from 'react-native-update';
import {getLogger} from '@siteed/react-native-logger';
const logger = getLogger('App');
import _updateConfig from './update.json';
import * as Sentry from '@sentry/react-native';
const {HKVisionDeviceModule} = NativeModules;
import DeviceBindScreen from './app/screens/DeviceBindScreen';
import CabinetVideoPage from './app/screens/CabinetVideoPage';
import CabnetNewsDetailPage from './app/screens/CabnetNewsDetailPage';
import SerialPortModule from './app/utils/SerialPortModule';
import CabinetProductsPage from './app/screens/CabinetProductsPage';
import BoxManagePage from './app/screens/BoxManagePage';
import ReserveQueryScreen from './app/screens/ReserveQueryScreen';
import DeviceReserveScreen from './app/screens/DeviceReserveScreen';
import {widthPercentageToDP} from 'react-native-responsive-hook';
import moment from 'moment';
import CabinetRepairPage from './app/screens/CabinetRepairPage';
import DeviceInfo from 'react-native-device-info';
import LogScreen from './app/screens/LogScreen';
import {AlertNotificationRoot} from 'react-native-alert-notification';
import WebviewPage from './app/screens/WebviewPage';
Sentry.init({
  dsn: 'https://76381c0d30111c5e1082f451c0d546cd@o226819.ingest.us.sentry.io/4507917300989952',

  // uncomment the line below to enable Spotlight (https://spotlightjs.com)
  // enableSpotlight: __DEV__,
});
const {appKey} = _updateConfig[Platform.OS];
const pushyClient = new Pushy({
  appKey,
  updateStrategy: null,
  debug: true,
  // 注意，默认情况下，在开发环境中不会检查更新
  // 如需在开发环境中调试更新，请设置debug为true
  // 但即便打开此选项，也仅能检查、下载热更，并不能实际应用热更。实际应用热更必须在release包中进行。
  // debug: true
});
const Stack = createStackNavigator();
function App(): React.JSX.Element {
  const isDarkMode = useColorScheme() === 'dark';

  const {
    checkUpdate,
    downloadUpdate,
    downloadAndInstallApk,
    switchVersion,
    updateInfo,
  } = usePushy();

  const connectCamera = () => {
    logger.info('连接摄像头设备 ');
    if (__DEV__) {
      return;
    }
    HKVisionDeviceModule &&
      HKVisionDeviceModule.login(
        'dev',
        '192.168.1.233',
        '8000',
        'admin',
        'Zng2024+',
      )
        .then(value => {
          ToastAndroid.show('连接摄像头成功', ToastAndroid.SHORT);
          logger.info('连接摄像头设备成功 ', value);
        })
        .catch(error => {
          ToastAndroid.show('连接摄像头失败', ToastAndroid.SHORT);
          logger.error('连接摄像头设备失败 ', error);
        });
  };

  const [date, setDate] = React.useState(new Date());
  useEffect(() => {
    checkUpdate();
    const sub6 = DeviceEventEmitter.addListener('checkUpdate', () => {
      checkUpdate();
    });
    logger.info('连接锁柜设备 ');
    SerialPortModule.connectDevice(
      '/dev/ttyS4',
      data => {
        // ToastUtil.show('发送消息:' + data);
      },
      data => {
        // ToastUtil.show('收到消息:' + data);
      },
    )
      .then(value => {
        logger.info('连接锁柜设备成功 ', value);
        console.log('connectDevice:', value);
        if (value) {
          ToastAndroid.show('连接快递柜成功', ToastAndroid.SHORT);
          connectCamera();
        } else {
          ToastAndroid.show('连接快递柜失败', ToastAndroid.SHORT);
          connectCamera();
        }
      })
      .catch(error => {
        logger.info('连接锁柜设备失败 ', error);
        ToastAndroid.show('连接快递柜失败', ToastAndroid.SHORT);
        connectCamera();
      });
    console.log('HKVisionDeviceModule:', HKVisionDeviceModule);
    if (!__DEV__) {
    }

    const requestPermissions = async () => {
      const permissions = [
        PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE,
        PermissionsAndroid.PERMISSIONS.CAMERA,
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      ];
      const grantedPermissions = await PermissionsAndroid.requestMultiple(
        permissions,
      );
      if (
        grantedPermissions[PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE] ===
          'granted' &&
        grantedPermissions[PermissionsAndroid.PERMISSIONS.CAMERA] ===
          'granted' &&
        grantedPermissions[
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
        ] === 'granted' &&
        grantedPermissions[
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
        ] === 'granted'
      ) {
      } else {
        ToastAndroid.show('请授予应用权限', ToastAndroid.SHORT);
      }
    };

    requestPermissions();

    const timer = setInterval(() => {
      setDate(new Date());
    }, 1000);
    return () => {
      clearTimeout(timer);
      sub6.remove();
      if (!__DEV__) {
        HKVisionDeviceModule &&
          HKVisionDeviceModule.logout &&
          HKVisionDeviceModule.logout();
      }
    };
  }, []);

  useEffect(() => {
    const downloadAndUpdate = async () => {
      await downloadUpdate();
      setTimeout(() => {
        switchVersion();
      }, 500);
    };
    if (updateInfo?.expired && updateInfo?.downloadUrl) {
      ToastAndroid.show(
        '发现新版本APK:V' + updateInfo.name + '，正在自动下载更新...',
        ToastAndroid.SHORT,
      );
      downloadAndInstallApk(updateInfo.downloadUrl);
    } else if (updateInfo?.update) {
      ToastAndroid.show(
        '发现新版本:V' + updateInfo.name + '，正在自动下载更新...',
        ToastAndroid.SHORT,
      );
      downloadAndUpdate();
    } else if (updateInfo?.upToDate) {
      ToastAndroid.show(
        DeviceInfo.getModel() + '已经是最新版本',
        ToastAndroid.SHORT,
      );
    } else {
      // ToastAndroid.show('检查更新失败', ToastAndroid.SHORT);
    }
  }, [updateInfo]);

  const headerRight = () => {
    return (
      <View style={{flexDirection: 'row'}}>
        <TouchableOpacity onPress={() => navigationRef.navigate('LogScreen')}>
          <Text
            style={{
              color: 'white',
              fontSize: widthPercentageToDP(2),
              paddingRight: widthPercentageToDP(1),
            }}>
            {moment(date).format('yyyy/MM/DD HH:mm:ss')}
          </Text>
        </TouchableOpacity>
      </View>
    );
  };

  return (
    <SafeAreaProvider>
      <GestureHandlerRootView style={{height: '100%', width: '100%'}}>
        <Provider store={store}>
          <TopView style={{height: '100%', width: '100%'}}>
            <AlertNotificationRoot>
              <NavigationContainer ref={navigationRef}>
                <Stack.Navigator>
                  <Stack.Screen
                    name="MainScreen"
                    options={{
                      headerStyle: {
                        backgroundColor: 'rgb(10, 183, 139)',
                      },
                      headerTintColor: '#fff',
                      headerTitleStyle: {
                        fontWeight: 'bold',
                      },
                      title: '首页',
                      headerTitleAlign: 'center',
                      headerRight: headerRight,
                    }}
                    component={MainScreen}
                  />

                  <Stack.Screen
                    name="DeviceBindScreen"
                    options={{
                      headerStyle: {
                        backgroundColor: 'rgb(10, 183, 139)',
                      },
                      headerTintColor: '#fff',
                      headerTitleStyle: {
                        fontWeight: 'bold',
                      },
                      title: '绑定',
                      headerTitleAlign: 'center',
                      headerRight: headerRight,
                      headerLeft: () => <View />,
                    }}
                    component={DeviceBindScreen}
                  />
                  <Stack.Screen
                    name="CabinetVideoPage"
                    options={{
                      headerShown: false,
                    }}
                    component={CabinetVideoPage}
                  />
                  <Stack.Screen
                    name="CabnetNewsDetailPage"
                    options={{
                      headerStyle: {
                        backgroundColor: 'rgb(10, 183, 139)',
                      },
                      headerTintColor: '#fff',
                      headerTitleStyle: {
                        fontWeight: 'bold',
                      },
                      title: '新闻详情',
                      headerTitleAlign: 'center',
                      headerRight: headerRight,
                    }}
                    component={CabnetNewsDetailPage}
                  />
                  <Stack.Screen
                    name="CabinetProductsPage"
                    options={{
                      headerStyle: {
                        backgroundColor: 'rgb(10, 183, 139)',
                      },
                      headerTintColor: '#fff',
                      headerTitleStyle: {
                        fontWeight: 'bold',
                      },
                      title: '柜体取件',
                      headerTitleAlign: 'center',
                      headerRight: headerRight,
                    }}
                    component={CabinetProductsPage}
                  />
                  <Stack.Screen
                    name="BoxManagePage"
                    options={{
                      headerStyle: {
                        backgroundColor: 'rgb(10, 183, 139)',
                      },
                      headerTintColor: '#fff',
                      headerTitleStyle: {
                        fontWeight: 'bold',
                      },
                      title: '柜体存放',
                      headerTitleAlign: 'center',
                      headerRight: headerRight,
                    }}
                    component={BoxManagePage}
                  />
                  <Stack.Screen
                    name="ReserveQueryScreen"
                    options={{
                      headerStyle: {
                        backgroundColor: 'rgb(10, 183, 139)',
                      },
                      headerTintColor: '#fff',
                      headerTitleStyle: {
                        fontWeight: 'bold',
                      },
                      title: '查询预约',
                      headerTitleAlign: 'center',
                      headerRight: headerRight,
                    }}
                    component={ReserveQueryScreen}
                  />
                  <Stack.Screen
                    name="DeviceReserveScreen"
                    options={{
                      headerStyle: {
                        backgroundColor: 'rgb(10, 183, 139)',
                      },
                      headerTintColor: '#fff',
                      headerTitleStyle: {
                        fontWeight: 'bold',
                      },
                      title: '设备预约',
                      headerTitleAlign: 'center',
                      headerRight: headerRight,
                    }}
                    component={DeviceReserveScreen}
                  />
                  <Stack.Screen
                    name="CabinetRepairPage"
                    options={{
                      headerStyle: {
                        backgroundColor: 'rgb(10, 183, 139)',
                      },
                      headerTintColor: '#fff',
                      headerTitleStyle: {
                        fontWeight: 'bold',
                      },
                      title: '设备报修',
                      headerTitleAlign: 'center',
                      headerRight: headerRight,
                    }}
                    component={CabinetRepairPage}
                  />
                  <Stack.Screen
                    name="WebviewPage"
                    options={{
                      headerStyle: {
                        backgroundColor: 'rgb(10, 183, 139)',
                      },
                      headerTintColor: '#fff',
                      headerTitleStyle: {
                        fontWeight: 'bold',
                      },
                      title: '',
                      headerTitleAlign: 'center',
                      headerRight: headerRight,
                    }}
                    component={WebviewPage}
                  />
                  <Stack.Screen
                    name="LogScreen"
                    options={{
                      headerStyle: {
                        backgroundColor: 'rgb(10, 183, 139)',
                      },
                      headerTintColor: '#fff',
                      headerTitleStyle: {
                        fontWeight: 'bold',
                      },
                      title: '日志',
                      headerTitleAlign: 'center',
                    }}
                    component={LogScreen}
                  />
                </Stack.Navigator>
              </NavigationContainer>
            </AlertNotificationRoot>
          </TopView>
        </Provider>
      </GestureHandlerRootView>
    </SafeAreaProvider>
  );
}
// export default App;
// 在根组件外加上PushyProvider后导出
export default function Root() {
  // 注意，在使用 PushyProvider 的当前组件中，无法直接调用 usePushy
  // 只有当前组件的子组件才能调用 usePushy
  return (
    <PushyProvider client={pushyClient}>
      {/* ↓ 整个应用的根组件放到PushyProvider中 */}
      <App />
    </PushyProvider>
  );
}
